package cn.ondraw.web.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.ondraw.web.domain.dto.PhoneInfoDTO;
import cn.ondraw.web.domain.dto.WxLoginInfoDTO;
import org.springframework.stereotype.Component;

@Component
public class WxLoginUtil {

    public String getAccessToken(String appId, String secret) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET".replace("APPID", appId).replace("SECRET", secret);
        String result = HttpUtil.get(requestUrl);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

    public WxLoginInfoDTO login(String appId, String secret, String jsCode) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code".replace("APPID", appId).replace("SECRET", secret).replace("JSCODE", jsCode);
        String result = HttpUtil.get(requestUrl);
        JSONObject jsonObject = JSONObject.parseObject(result);
        WxLoginInfoDTO wxLoginInfo = new WxLoginInfoDTO();
        wxLoginInfo.setSessionKey(jsonObject.getString("session_key"));
        wxLoginInfo.setOpenId(jsonObject.getString("openid"));
        wxLoginInfo.setUnionId(jsonObject.getString("unionid"));
        return wxLoginInfo;
    }

    public PhoneInfoDTO getPhoneNumber(String accessToken, String code) {
        String requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", accessToken);
        JSONObject requestBody = new JSONObject();
        requestBody.put("code", code);
        String result = ((HttpRequest) HttpRequest.post(requestUrl).header("Content-Type", "application/json")).body(JSON.toJSONString(requestBody)).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        String phoneString = jsonObject.getString("phone_info");
        JSONObject phoneJson = JSONObject.parseObject(phoneString);
        PhoneInfoDTO phoneInfo = new PhoneInfoDTO();
        phoneInfo.setCountryCode(phoneJson.getString("countryCode"));
        phoneInfo.setPhoneNumber(phoneJson.getString("phoneNumber"));
        phoneInfo.setPurePhoneNumber(phoneJson.getString("purePhoneNumber"));
        return phoneInfo;
    }
}
